
#import "XMGADViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "XMGADItem.h"
#import <MJExtension/MJExtension.h>
#import "UIImageView+WebCache.h"

#import "ViewController.h"


#import "GRJMacros.h"

/*
    解析完整URL =》 找？基本的url和参数隔开
    http://mobads.baidu.com/cpro/ui/mads.php ?code2=phcqnauGuHYkFMRquANhmgN_IauBThfqmgKsUARhIWdGULPxnz3vndtkQW08nau_I1Y1P1Rhmhwz5Hb8nBuL5HDknWRhTA_qmvqVQhGGUhI_py4MQhF1TvChmgKY5H6hmyPW5RFRHzuET1dGULnhuAN85HchUy7s5HDhIywGujY3P1n3mWb1PvDLnvF-Pyf4mHR4nyRvmWPBmhwBPjcLPyfsPHT3uWm4FMPLpHYkFh7sTA-b5yRzPj6sPvRdFhPdTWYsFMKzuykEmyfqnauGuAu95Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiu9mLfqHbD_H70hTv6qnHn1PauVmynqnjclnj0lnj0lnj0lnj0lnj0hThYqniuVujYkFhkC5HRvnB3dFh7spyfqnW0srj64nBu9TjYsFMub5HDhTZFEujdzTLK_mgPCFMP85Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiuBnHfdnjD4rjnvPWYkFh7sTZu-TWY1QW68nBuWUHYdnHchIAYqPHDzFhqsmyPGIZbqniuYThuYTjd1uAVxnz3vnzu9IjYzFh6qP1RsFMws5y-fpAq8uHT_nBuYmycqnau1IjYkPjRsnHb3n1mvnHDkQWD4niuVmybqniu1uy3qwD-HQDFKHakHHNn_HR7fQ7uDQ7PcHzkHiR3_RYqNQD7jfzkPiRn_wdKHQDP5HikPfRb_fNc_NbwPQDdRHzkDiNchTvwW5HnvPj0zQWndnHRvnBsdPWb4ri3kPW0kPHmhmLnqPH6LP1ndm1-WPyDvnHKBrAw9nju9PHIhmH9WmH6zrjRhTv7_5iu85HDhTvd15HDhTLTqP1RsFh4ETjYYPW0sPzuVuyYqn1mYnjc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ic) IBOutlet UIButton *jumpButton;
@property (weak, nonatomic) IBOutlet UIImageView *adView;
@property (weak, nonatomic) IBOutlet UIImageView *launchImageView;
@property (nonatomic, strong) XMGADItem *item;
@property (nonatomic, weak) NSTimer *timer;
@end

@implementation XMGADViewController
// 为什么要在广告界面展示启动图片，让用户一直觉得程序在启动的过程中
// 占位视图：先搞个view占着这个位置，等view确定了之后，就往占位视图添加了
// 当一个view的层次结构，确定了之后，但是里面具体子控件还不确定，可以使用占位视图思想.
// 启动图片都可以使用，直接往项目中导入.
// 根据不同屏幕尺寸，去加载不同图片


- (IBAction)jump {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *viewC = [storyboard instantiateInitialViewController];
    
    // 进入到主框架界面 修改窗口根控制器
    [UIApplication sharedApplication].keyWindow.rootViewController = viewC;
    // 销毁定时器
    [_timer invalidate];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 设置启动图片
    [self setupLaunchScreenImage];
    
    // 完整url = 基本url + 请求参数
    // json在线解析器 ： http://json.cn
    // 加载广告界面 -> 广告数据是活 -》 向服务器请求数据 -> 查看接口文档 -》 验证接口是否正确 -> 解析数据（找出有用的数据）(w_picurl:广告界面,ori_curl:点击广告界面进入网页,w,h)
    [self loadAdData];
    
    // 创建定时器:把target给强引用
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];

}

// 每隔一秒钟就会调用
- (void)timeChange
{
    // 按钮文字 如果一闪一闪 就是按钮的样式不对，system
    static int i = 3;
    i--;
    // 修改按钮文字
    [_jumpButton setTitle:[NSString stringWithFormat:@"跳过 (%d)",i] forState:UIControlStateNormal];
    
    if (i < 0) { // 3秒过完
        [self jump];
    }
    
}

// 加载广告数据
- (void)loadAdData
{
    // "Request failed: unacceptable content-type: text/html"
    // http请求过程
    // http协议常识
    // 1.创建请求会话管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    // 2.创建请求参数字典
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"code2"] = XMGCode2;
    
    // 2.发送请求 get,post 查看接口文档
    [mgr GET:@"http://mobads.baidu.com/cpro/ui/mads.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 成功获取到数据
        NSDictionary *adDict = [responseObject[@"ad"] firstObject];
        
        // 设计模型
        // 字典转模型
        XMGADItem *item =  [XMGADItem mj_objectWithKeyValues:adDict];
        _item = item;
        
        // 修改xib控件位置，不好使，直接手动创建控件
        // 手动创建UIImageView
        UIImageView *adView = [[UIImageView alloc] init];
        adView.userInteractionEnabled = YES;
        
        // 尺寸和位置
        if (item.w) { // 注意：除以一个数，最好做判断，是否大于0
            CGFloat h = kScreenWidth / item.w * item.h;
            adView.frame = CGRectMake(0, 0, kScreenWidth, h);
        }
        
        // 添加点按手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
        [adView addGestureRecognizer:tap];
        
        
        // 把模型的内容展示到控件上
        // 加载网络图片 -》 SDWebImage
        [adView sd_setImageWithURL:[NSURL URLWithString:item.w_picurl]];
        
        NSLog(@"----->>>.>%@",item.w_picurl);
        
        [_adView addSubview:adView];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
        
    }];
}

// 点击广告图片就会调用
- (void)tap
{
    // 用safari打开网页
    NSURL *url = [NSURL URLWithString:_item.ori_curl];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        // 使用safari打开网页
        [[UIApplication sharedApplication] openURL:url];
    }
}
// 设置启动图片
- (void)setupLaunchScreenImage
{
    
    if (iPhone6P) { // iPhone6P
        _launchImageView.image = [UIImage imageNamed:@"LaunchImage-800-Portrait-736h@3x"];
    } else if (iPhone6) {
        _launchImageView.image = [UIImage imageNamed:@"LaunchImage-800-667h"];
    } else if (iPhone5) {
        _launchImageView.image = [UIImage imageNamed:@"LaunchImage-700-568h"];
    } else if (iPhone4) {
        _launchImageView.image = [UIImage imageNamed:@"LaunchImage"];
    }
}

@end
